package cn.com.qingz.core.utils;

import java.lang.reflect.Field;

import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;

import cn.com.qingz.core.model.FiledComment;
import cn.com.qingz.core.model.UpdateUserInfo;
import cn.com.qingz.modules.user.model.SampleHouse;
import cn.com.qingz.modules.user.model.Version;

/**
 * 建表生成工具   javabean 生成数据库建表语句.
 * @author jiulong.hu 下午5:35:57
 *
 */
public class CreateDDLGen {

	/**
	 * 生成建表语句
	 * @param clazz  实体类
	 * @param deleteFrist  是否删除之前同名的表
	 * @return
	 */
	public static String getCreateDDL(Class<?> clazz ,boolean deleteFrist) {
		StringBuilder sb = new StringBuilder();
		Table tname = clazz.getAnnotation(Table.class);
		if(deleteFrist){
			sb.append("DROP TABLE IF EXISTS " + tname.name() + " ;");
		}
		sb.append("CREATE TABLE " + tname.name() + " (\n");
		Field[] methods = clazz.getDeclaredFields();
		String id = "";
		for (Field field : methods) {
			Transient t = field.getAnnotation(Transient.class);
			if (t != null) {
				continue ;
			}
			FiledComment comment = field.getAnnotation(FiledComment.class);
			sb.append("\t" + field.getName() + " ");
			sb.append(typeChange(field.getType().getSimpleName()));
			sb.append(" DEFAULT NULL");
			if(comment !=null ){
				sb.append(" COMMENT '" + comment.value() +"'");
			}
			sb.append(",\n");
			Id ifid = field.getAnnotation(Id.class);
			if (ifid != null) {
				id = field.getName();
			}
		}

		if (clazz.getSuperclass().getName().equals("cn.com.qingz.core.model.UpdateUserInfo")) {
			Field[] parentMethods = UpdateUserInfo.class.getDeclaredFields();
			for (Field field : parentMethods) {
				sb.append("\t" + field.getName() + " ");
				sb.append(typeChange(field.getType().getSimpleName()));
				FiledComment comment = field.getAnnotation(FiledComment.class);
				sb.append(" DEFAULT NULL");
				if(comment !=null ){
					sb.append(" COMMENT '" + comment.value() +"'");
				}
				sb.append(",\n");
			}
			sb.append("locked tinyint(4) DEFAULT NULL,");
		}
		
		sb.append("\tPRIMARY KEY (" + id + ")\n");
		sb.append(") ENGINE=InnoDB   DEFAULT CHARSET=utf8;");
		return sb.toString();
	}

	public static String typeChange(String name) {
		if ("String".equals(name)) {
			return "varchar (128)";
		}
		if ("Date".equals(name)) {
			return "datetime";
		}
		if ("Long".equals(name)) {
			return "bigint(10)";
		}
		return name;
	}

	public static void main(String[] args) {
		 
		System.out.println(getCreateDDL(SampleHouse.class , true));
//		System.out.println(getCreateDDL(Brand.class , true));
//		System.out.println(getCreateDDL(Category.class , true));
	}
}
